import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import '../../app_views.dart';

/// 首页控制器 - Home Controller
///
/// 负责首页状态管理和业务逻辑处理
/// Responsible for home page state management and business logic processing
class HomeLogic extends GetxController {
  /// 状态管理 - State management
  final Rx<HomeState> state = HomeState().obs;

  /// API仓库 - API repository
  final _apiRepository = Get.find<ApiRepository>();

  @override
  void onInit() {
    super.onInit();
    _initializeState();
    _loadInitialData();
  }

  @override
  void onClose() {
    super.onClose();
  }

  /// 初始化状态 - Initialize state
  /// 设置首页的初始状态和推荐功能列表
  /// Sets initial state and recommended features list for home page
  void _initializeState() {
    state.value.todayInfo = null;
    state.value.errorMessage = null;
    state.value.isLoading = false;
    state.value.isRefreshing = false;
    state.value.isLoadingFortune = false;
    state.value.isLoadingCalendar = false;
    state.value.dailyFortune = null;
    state.value.calendarInfo = null;
    state.value.recommendedFeatures = [
      const FeatureItem(
        title: '万年历',
        description: '查看详细的万年历信息',
        route: '/calendar',
        type: 'calendar',
        color: '#6366F1',
      ),
      const FeatureItem(
        title: '运势查询',
        description: '查看今日运势和建议',
        route: '/fortune',
        type: 'fortune',
        color: '#F59E0B',
      ),
      const FeatureItem(
        title: '工具箱',
        description: '实用的生活工具集合',
        route: '/tools',
        type: 'tools',
        color: '#10B981',
      ),
      const FeatureItem(
        title: '学堂',
        description: '学习传统文化知识',
        route: '/classroom',
        type: 'classroom',
        color: '#8B5CF6',
      ),
    ];
  }

  /// 加载初始数据 - Load initial data
  /// 并行加载今日信息、运势和万年历数据
  /// Load today's info, fortune and calendar data in parallel
  Future<void> _loadInitialData() async {
    await Future.wait([
      loadDailyFortune(),
      loadCalendarInfo(),
      loadTodayInfo(),
    ]);
  }

  /// 刷新所有数据 - Refresh all data
  /// 用户下拉刷新时调用
  /// Called when user pulls to refresh
  Future<void> refreshAllData() async {
    if (state.value.isRefreshing) return;

    state.value.isRefreshing = true;
    
    try {
      await Future.wait([
        loadDailyFortune(),
        loadCalendarInfo(),
        refreshTodayInfo(),
      ]);
    } finally {
      state.value.isRefreshing = false;
    }
  }

  /// 加载每日运势 - Load daily fortune
  /// 获取今日运势数据并更新状态
  /// Gets today's fortune data and updates state
  Future<void> loadDailyFortune() async {
    try {
      state.value.isLoadingFortune = true;

      // 模拟API调用 - Simulate API call
      await Future.delayed(const Duration(seconds: 1));

      state.value.dailyFortune = {
        'overall': '今日运势较好，适合进行重要决策',
        'love': '感情运势平稳，单身者有机会遇到心仪对象',
        'career': '工作运势上升，容易得到上司认可',
        'wealth': '财运一般，不宜进行大额投资',
        'health': '身体状况良好，注意适当休息',
      };
    } catch (e) {
      debugPrint('加载每日运势失败: $e');
      state.value.errorMessage = '加载运势失败: $e';
    } finally {
      state.value.isLoadingFortune = false;
    }
  }

  /// 加载万年历信息 - Load calendar information
  /// 获取今日万年历数据并更新状态
  /// Gets today's calendar data and updates state
  Future<void> loadCalendarInfo() async {
    try {
      state.value.isLoadingCalendar = true;

      final today = DateTime.now();
      final dateString =
          '${today.year}-${today.month.toString().padLeft(2, '0')}-${today.day.toString().padLeft(2, '0')}';

      final result = await _apiRepository.getCalendarInfo(dateString);

      if (result.success && result.data != null) {
        state.value.calendarInfo = result.data;
      }
    } catch (e) {
      debugPrint('加载万年历信息失败: $e');
    } finally {
      state.value.isLoadingCalendar = false;
    }
  }

  /// 从万年历数据更新今日信息 - Update today info from calendar data
  void _updateTodayInfoFromCalendar(CalendarInfo calendarInfo) {
    final today = DateTime.now();
    final todayInfo = TodayInfo(
      solarDate: '${today.year}年${today.month}月${today.day}日',
      lunarDate: calendarInfo.lunarDate,
      weekday: _getWeekdayName(today.weekday),
      constellation: calendarInfo.constellation,
      chineseZodiac: calendarInfo.zodiac,
      ganZhi: calendarInfo.ganzhi,
      solarTerm: calendarInfo.solarTerm,
      festivals: calendarInfo.festivals,
      lunarFestivals: calendarInfo.lunarFestivals,
      suitable: calendarInfo.yi,
      avoid: calendarInfo.ji,
      fiveElements: calendarInfo.fiveElements,
      nayin: calendarInfo.nayin,
      fortuneScore: 75,
      luckyNumber: 8,
      luckyColor: '紫色',
      luckyDirection: '东方',
      suggestion: '今日宜保持积极心态',
      warning: '',
      auspiciousTime: '09:00-11:00',
    );

    state.value.todayInfo = todayInfo;
    state.value.errorMessage = null;
    state.value.isLoading = false;
  }

  /// 获取星期名称 - Get weekday name
  String _getWeekdayName(int weekday) {
    const weekdays = ['一', '二', '三', '四', '五', '六', '日'];
    return '星期${weekdays[weekday - 1]}';
  }

  /// 处理功能项点击 - Handle feature item tap
  void onFeatureTap(FeatureItem feature) {
    Get.toNamed(feature.route);
  }

  /// 导航到万年历 - Navigate to calendar
  void navigateToCalendar() {
    Get.toNamed('/calendar');
  }

  /// 导航到占卜工具 - Navigate to tools
  void navigateToTools() {
    Get.toNamed('/tools');
  }

  /// 导航到命理分析 - Navigate to analysis
  void navigateToAnalysis() {
    Get.toNamed('/analysis');
  }

  /// 导航到功能页面 - Navigate to feature page
  void navigateToFeature(String route) {
    Get.toNamed(route);
  }

  /// 刷新首页数据 - Refresh home data (绑定下拉刷新)
  Future<void> refreshHomeData() async {
    await refreshAllData();
  }

  /// 处理运势项点击 - Handle fortune item tap
  void onFortuneTap(FortuneItem fortune) {
    Get.snackbar(
      fortune.title,
      '${fortune.title}详情页面正在开发中',
      snackPosition: SnackPosition.BOTTOM,
    );
  }

  /// 加载今日信息 - Load today's info
  /// 获取今日万年历和基础运势信息
  /// Gets today's calendar and basic fortune info
  Future<void> loadTodayInfo() async {
    try {
      state.value.isLoading = true;

      final today = DateTime.now();
      final dateString =
          '${today.year}-${today.month.toString().padLeft(2, '0')}-${today.day.toString().padLeft(2, '0')}';

      // 获取万年历信息 - Get calendar info
      final calendarResult = await _apiRepository.getCalendarInfo(dateString);

      if (calendarResult.success && calendarResult.data != null) {
        _updateTodayInfoFromCalendar(calendarResult.data!);
      } else {
        // 如果API失败，使用默认数据 - Use default data if API fails
        _setDefaultTodayInfo();
      }

      state.value.errorMessage = null;
      state.value.isLoading = false;
    } catch (e) {
      debugPrint('加载今日信息失败: $e');
      state.value.errorMessage = '加载失败: $e';
      state.value.isLoading = false;
    }
  }

  /// 刷新今日信息 - Refresh today info
  Future<void> refreshTodayInfo() async {
    try {
      state.value.isRefreshing = true;

      final today = DateTime.now();
      final dateString =
          '${today.year}-${today.month.toString().padLeft(2, '0')}-${today.day.toString().padLeft(2, '0')}';

      // 获取万年历信息 - Get calendar info
      final calendarResult = await _apiRepository.getCalendarInfo(dateString);

      if (calendarResult.success && calendarResult.data != null) {
        _updateTodayInfoFromCalendar(calendarResult.data!);
      }

      state.value.errorMessage = null;
      state.value.isRefreshing = false;
    } catch (e) {
      debugPrint('刷新今日信息失败: $e');
      state.value.errorMessage = '刷新失败: $e';
      state.value.isRefreshing = false;
    }
  }

  /// 设置默认今日信息 - Set default today info
  /// 当API调用失败时使用默认数据
  /// Use default data when API call fails
  void _setDefaultTodayInfo() {
    final today = DateTime.now();
    final todayInfo = TodayInfo(
      solarDate: '${today.year}年${today.month}月${today.day}日',
      lunarDate: '农历${today.month}月${today.day}日',
      weekday: _getWeekdayName(today.weekday),
      constellation: '水瓶座',
      chineseZodiac: '龙',
      ganZhi: '甲辰',
      solarTerm: '立春',
      festivals: [],
      lunarFestivals: [],
      suitable: ['祈福', '出行', '会友'],
      avoid: ['动土', '开仓', '出货财'],
      fiveElements: '木',
      nayin: '佛灯火',
      fortuneScore: 75,
      luckyNumber: 8,
      luckyColor: '紫色',
      luckyDirection: '东方',
      suggestion: '今日宜保持积极心态',
      warning: '',
      auspiciousTime: '09:00-11:00',
    );

    state.value.todayInfo = todayInfo;
    state.value.errorMessage = null;
    state.value.isLoading = false;
  }

  /// 处理错误状态 - Handle error state
  /// 统一处理各种错误情况
  /// Unified handling of various error scenarios
  void _handleError(String error) {
    state.value.errorMessage = error;
    state.value.isLoading = false;
    state.value.isRefreshing = false;
  }

  /// 清除错误信息 - Clear error message
  /// 用户重试或刷新时调用
  /// Called when user retries or refreshes
  void clearError() {
    state.value.errorMessage = null;
    state.refresh();
  }
}
